package com.charles.web;


import com.charles.core.bus.EventBusCenter;
import com.charles.core.event.ViewEvent;
import com.charles.entity.ShortUrl;
import com.charles.vo.R;
import com.charles.vo.param.ShortUrlParam;
import com.charles.service.ShortUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.Optional;

/**
 * @author charles
 * @date 2022/9/4 13:42
 */
@Controller
@Validated
@Slf4j
public class ShortUrlController {

    @Autowired
    private ShortUrlService shortUrlService;

    @Autowired
    private EventBusCenter eventBusCenter;

    /**
     * 压缩url
     *
     * @param shortUrlParam
     * @return
     */
    @PostMapping("/shorten")
    @ResponseBody
    public String shorten(@RequestBody ShortUrlParam shortUrlParam) {
        return shortUrlService.shorten(shortUrlParam);
    }

    /**
     * 保存短链映射关系
     *
     * @param shortUrl
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public R saveShortUrl(@RequestBody ShortUrl shortUrl) {
        shortUrlService.save(shortUrl);
        return R.ok("保存成功", "");
    }

    /**
     * 根据短链压缩码获取映射关系
     *
     * @param compressCode
     * @return
     */
    @GetMapping("/get-origin-url")
    @ResponseBody
    public String getOriginUrl(@RequestParam(required = true) String compressCode) {
        ShortUrl urlEntity = shortUrlService.getOriginUrl(compressCode);
        return Optional.ofNullable(urlEntity).map(ShortUrl::getOriginUrl).orElse("");
    }

    /**
     * 重定向
     *
     * @param compressCode
     * @return
     */
    @GetMapping("/{compressCode}")
    public String redirect(@PathVariable(value = "compressCode") String compressCode) {
        ShortUrl shortUrl = shortUrlService.getOriginUrl(compressCode);
        log.info("请求短链：{},原始链接：{}", compressCode, Optional.ofNullable(shortUrl).map(ShortUrl::getOriginUrl).orElse(""));
        if (Objects.isNull(shortUrl)) {
            throw new RuntimeException("短链接获取不到");
        }
        eventBusCenter.postAsync(ViewEvent.builder().shortUrl(shortUrl).build());
        return "redirect:" + shortUrl.getOriginUrl();
    }
}
